import db from "@/server/connector/db";
import log from "@/server/log";
import AppError from "@/shared/app-error";
import { PostSummary } from "@/shared/types";
import { Post, User } from "@prisma/client";
import App from "next/app";

async function getRecommendedPosts(): Promise<PostSummary[]> {
  return await db.post.findMany({
    select: {
      id: true,
      title: true,
      contentType: true,
      personal: true,
      createTime: true,
      updateTime: true,
      authorId: true,
    },
    where: { personal: false, deleteTime: null },
    orderBy: { createTime: "desc" },
    take: 10,
  });
}

async function getPostById({ postId, me }: { postId: string; me?: User | null }): Promise<Post | null> {
  if (postId === "error") {
    throw AppError.unhandledError("是错误呀 ;-P");
  }

  const post = await db.post.findUnique({ where: { id: postId } });
  if (!post) return null; // 没有不返
  if (!post.personal) return post; // 非个人的返
  if (post.authorId === me?.id) return post; // 个人的且是自己的返
  return null;
}

async function getMyPostById({ postId, me }: { postId: string; me: User }): Promise<Post | null> {
  return await db.post.findUnique({ where: { id: postId, authorId: me.id } });
}

const postsService = {
  getMyPostById,
  getPostById,
  getRecommendedPosts,
};

export default postsService;
